package com.changgou.pay.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.pay.service.WeiXinPayService;
import com.github.wxpay.sdk.WXPayUtil;
import entity.Result;
import entity.StatusCode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
public class WeiXinPayController {

    @Value("${mq.pay.exchange.order}")
    private String exchange;

    @Autowired
    private WeiXinPayService weiXinPayService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /***
     * 发送订单信息到微信服务器，并获取二维码网址
     * @return
     */
    @RequestMapping(value = "/create/native")
    public Result getNative(@RequestParam Map<String, String> param) throws Exception {
        Map<String, String> resultMap = weiXinPayService.getNative(param);
        return new Result(true, StatusCode.OK, "创建二维码预付订单成功！", resultMap);
    }

    /***
     * 查询支付状态
     * @param out_trade_no
     * @return
     */
    @GetMapping(value = "/status/query")
    public Result queryStatus(String out_trade_no) throws Exception {
        Map<String, String> resultMap = null;
        try {
            resultMap = weiXinPayService.queryPayStatus(out_trade_no);
            return new Result(true, StatusCode.OK, "查询状态成功！", resultMap);
        } catch (Exception e) {
            return new Result(false, StatusCode.ERROR, "查询失败！");
        }

    }

    /****
     * 支付回调
     * @param request
     * @return
     */
    @RequestMapping(value = "/notify/url")
    public String notifyUrl(HttpServletRequest request) throws Exception {
        //读取回调的数据
        InputStream inputStream = request.getInputStream();
        //使用字节数组输出流读取数据
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        outputStream.close();
        inputStream.close();

        //获取的数据装换为map
        String resultXml = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
        Map<String, String> resultMap = WXPayUtil.xmlToMap(resultXml);
        //获取attach中的消息队列
        Map<String, String> attachMap = JSON.parseObject(resultMap.get("attach"), Map.class);
        String routingKey = attachMap.get("routingKey");

        //获取到信息之后发送给RabbitMQ
        rabbitTemplate.convertAndSend(exchange, routingKey, JSON.toJSONString(resultMap));

        //响应数据设置，告诉微信服务器已经收到回调信息，不然微信服务器还会发送多次请求
        Map respMap = new HashMap();
        respMap.put("return_code", "SUCCESS");
        respMap.put("return_msg", "OK");
        return WXPayUtil.mapToXml(respMap);
    }

    /****
     * 关闭支付
     * @param orderId
     * @return
     * @throws Exception
     */
    @RequestMapping("/closePay")
    public Result closePay(Long orderId) throws Exception {
        Map<String, String> resultMap = weiXinPayService.closePay(orderId);
        return new Result(true, StatusCode.OK, "关闭成功", resultMap);
    }
}
